package com.fireandsword.system.handle;

import com.fireandsword.system.domain.vo.ResultVo;
import com.fireandsword.system.enums.ResultCode;
import com.fireandsword.system.exception.APIException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author Immortal
 * @version 1.0
 * @description TODO
 * @date 2023/12/28 14:25
 */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionAdvice {


    @ExceptionHandler({BindException.class})
    public ResultVo MethodArgumentNotValidException(BindException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(ResultCode.PARAM_ERROR,objectError.getDefaultMessage());
    }


    @ExceptionHandler({APIException.class})
    public ResultVo APIException(APIException e) {
        log.error("业务自定义异常", e);
        return new ResultVo(e.getCode(),e.getMsg(),e.getMessage());
    }
}
